package com.guoyansoft.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 刘耀诚
 * 该类用于实现日期转换
 */
@Component
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        Date date=null;
        if(source==null){
            throw new RuntimeException("日期有误！");
        }
        if(source.matches("\\d{4}-\\d{2}-\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            try {
                date=sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        else if(source.matches("\\d{4}/\\d{2}/\\d{2}")){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
            try {
                date= sdf.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException("日期有误！");
            }
        }
        return date;
    }
}
